package cn.tianyun.pethome.fastdfs;


import cn.tianyun.pethome.basic.util.AjaxResult;
import cn.tianyun.pethome.basic.util.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastDfs")
//上传（post）、删除(del)
public class FastDfsController {

    @PostMapping
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file)  {

        try {
            byte[] bytes = file.getBytes();//上传的二进制流
            String filename = file.getOriginalFilename();
            // xxx.jpg，得到后缀名
            String extName = filename.substring(filename.lastIndexOf(".")+1);
            System.out.println(extName);
            //调用工具类里卖弄的方法，将bytes和extName作参数传入，获取路径
            String path = FastdfsUtil.upload(bytes, extName);
            //将路径以AjaxResult的方式传给前端，path就是路径
            return AjaxResult.creat().setSuccess(true).setResultObj(path);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.creat().setSuccess(false).setMsg("上传失败！"+e.getMessage());
        }

    }


    //    /group1/M00/00/A7/rBE3kWD3hEmAObWQAACIaoIycWk311.jpg
    @DeleteMapping
    public AjaxResult delete(@RequestParam(required = true,value = "path") String  path) throws IOException {
        try {
            String pathTmp = path.substring(1); // goup1/xxxxx/yyyy
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// /xxxxx/yyyy
            System.out.println(groupName);
            System.out.println(remotePath);
            FastdfsUtil.delete(groupName,remotePath);
            return AjaxResult.creat().setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.creat().setSuccess(false).setMsg("删除失败！"+e.getMessage());
        }
    }
}